package com.example.administrator.ygddriver.map;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.search.core.RouteLine;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteLine;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.baidu.mapapi.utils.DistanceUtil;
import com.baidu.mapapi.utils.SpatialRelationUtil;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BaiduNaviManagerFactory;
import com.baidu.navisdk.adapter.IBNRoutePlanManager;
import com.baidu.navisdk.adapter.IBNTTSManager;
import com.baidu.navisdk.adapter.IBaiduNaviManager;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.administrator.ygddriver.R;
import com.example.administrator.ygddriver.base.BaseActivity;
import com.example.administrator.ygddriver.base.BaseBean;
import com.example.administrator.ygddriver.base.BaseHint;
import com.example.administrator.ygddriver.base.UserBean;
import com.example.administrator.ygddriver.liteorm.LiteOrmTools;
import com.example.administrator.ygddriver.order.getorder.PickUpRequestBean;
import com.example.administrator.ygddriver.order.outorder.SecretaxbRequestBean;
import com.example.administrator.ygddriver.order.outorder.ToSendRequestBean;
import com.example.administrator.ygddriver.order.specific.SpecificActivity;
import com.example.administrator.ygddriver.tool.CustomPopWindow;
import com.example.administrator.ygddriver.tool.OkGoRequests;
import com.example.administrator.ygddriver.tool.SimpleToolbar;
import com.example.administrator.ygddriver.tool.UrlValuse;
import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.zaaach.citypicker.CityPicker;
import com.zaaach.citypicker.adapter.OnPickListener;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.model.LocatedCity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class SendMapActivity extends BaseActivity implements OnGetRoutePlanResultListener {
    private boolean hasInitSuccess = false;
    private static final String[] authBaseArr = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION
    };
    private String mSDCardPath = null;
    private static final int authBaseRequestCode = 1;
    private static final String APP_FOLDER_NAME = "YGDDriver";
    private BNRoutePlanNode mStartNode = null;
    private TextView mNextTv, mPlaceTv, mDistanceTv, mStartTv;
    static final String ROUTE_PLAN_NODE = "routePlanNode";
    private PickUpRequestBean.ResultBean getOrderBean;
    private ToSendRequestBean.ResultBean outOrderBean;
    private MyLocationListener myListener = new MyLocationListener();
    public LocationClient mLocationClient = null;
    private Double longitude, latitude;
    private String city;
    private SimpleToolbar simpleToolbar;
    private BaiduMap mBaiduMap;
    private MapView mMapView;
    // 搜索相关
    RoutePlanSearch mSearch = null;    // 搜索模块，也可去掉地图模块独立使用
    //判断是从接件还是送件 跳转的 1为接件 2为送件
    private int tag;
    private LatLng latLng1, latLng;
    private CustomPopWindow mCustomPopWindow;
    private String id, token, driverPhone;
    //确认收件成功 1为成功 不可点击 0为 还未确认 可以点击
    private int getTag = 0;

    @Override
    public int initLayout() {
        return R.layout.activity_send_map;
    }

    @Override
    public void initView() {
        LiteOrmTools.getInformation(UserBean.class, this, new LiteOrmTools.On<UserBean>() {
            @Override
            public void hasData(UserBean data) {
                id = data.getC_id();
                token = data.getC_token();
                driverPhone = data.getC_account();
            }
        }, new LiteOrmTools.OFF() {
            @Override
            public void noData() {

            }
        });

        mMapView = findViewById(R.id.activity_send_map_mv);
        mBaiduMap = mMapView.getMap();
        mStartTv = findViewById(R.id.activity_send_map_start_tv);
        simpleToolbar = findViewById(R.id.activity_send_map_stb);
        mPlaceTv = findViewById(R.id.activity_send_map_place_tv);
        mDistanceTv = findViewById(R.id.activity_send_map_distance_tv);
        Bundle bundle = getIntent().getExtras();
        getOrderBean = bundle.getParcelable("getOrderBean");
        outOrderBean = bundle.getParcelable("outOrderBean");
        tag = bundle.getInt("tag");
        mNextTv = findViewById(R.id.activity_send_map_next_tv);
        mStartTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (initDirs()) {
                    initNavi();
                }
                if (BaiduNaviManagerFactory.getBaiduNaviManager().isInited()) {

                }
            }
        });
        mNextTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (tag == 1) {
                    Intent intent = new Intent(SendMapActivity.this, SpecificActivity.class);
                    intent.putExtra("branches", getOrderBean.getC_branches());
                    startActivity(intent);
                    finish();
                } else if (tag == 2) {
                    if (getTag == 0) {
                        mLocationClient.start();
                        //判断是否到达范围

                        if (SpatialRelationUtil.isCircleContainsPoint(latLng1, 250, latLng)) {
                            initReachDestinationHtml(outOrderBean.getC_id(), token, v);

                        } else {
                            Toast.makeText(SendMapActivity.this, "还未到达送件范围请确认", Toast.LENGTH_SHORT).show();
                        }
                    }
                }

            }
        });
        // 初始化搜索模块，注册事件监听
        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(this);
    }

    @Override
    public void initDate() {
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        setLocationClientOption();

        setSimpleToolbar();
        if (tag == 1) {
            mPlaceTv.setText(getOrderBean.getC_networklocation());
            mNextTv.setText("开始接件");
        } else if (tag == 2) {

            mPlaceTv.setText(outOrderBean.getC_address());
            mNextTv.setText("等待送达");
            mNextTv.setBackgroundColor(Color.parseColor("#FF9E9E9E"));

        }


    }

    private void setSimpleToolbar() {
        simpleToolbar.setMainTitle("前往网点");
        simpleToolbar.setMainTitleColor("#000000");
        simpleToolbar.setBackIv(R.mipmap.left_title);
        simpleToolbar.setToolColor("#ffffff");
        simpleToolbar.setBackIvClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                //返回结果
                setResult(0x001, intent);
                finish();
            }
        });
    }


//    private boolean hasBasePhoneAuth() {
//        PackageManager pm = this.getPackageManager();
//        for (String auth : authBaseArr) {
//            if (pm.checkPermission(auth, this.getPackageName()) != PackageManager.PERMISSION_GRANTED) {
//                return false;
//            }
//        }
//        return true;
//    }

    private void initNavi() {
        // 申请权限
        PermissionsUtil.requestPermission(this, new PermissionListener() {
            @Override
            public void permissionGranted(@NonNull String[] permissions) {

                BaiduNaviManagerFactory.getBaiduNaviManager().init(SendMapActivity.this,
                        mSDCardPath, APP_FOLDER_NAME, new IBaiduNaviManager.INaviInitListener() {

                            @Override
                            public void onAuthResult(int status, String msg) {
                                String result;
                                if (0 == status) {
                                    result = "key校验成功!";
                                } else {
                                    result = "key校验失败, " + msg;
                                }
                                Toast.makeText(SendMapActivity.this, result, Toast.LENGTH_LONG).show();
                            }

                            @Override
                            public void initStart() {
                                Toast.makeText(SendMapActivity.this, "百度导航引擎初始化开始", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void initSuccess() {
                                Toast.makeText(SendMapActivity.this, "百度导航引擎初始化成功", Toast.LENGTH_SHORT).show();
                                hasInitSuccess = true;
                                routeplanToNavi(BNRoutePlanNode.CoordinateType.BD09LL, longitude, latitude, city, city);
//                                初始化tts
                                initTTS();
                                mLocationClient.start();
                            }

                            @Override
                            public void initFailed() {
                                Toast.makeText(SendMapActivity.this, "百度导航引擎初始化失败", Toast.LENGTH_SHORT).show();
                            }
                        });
            }

            @Override
            public void permissionDenied(@NonNull String[] permissions) {
                return;
            }
        }, authBaseArr);


    }


    private boolean initDirs() {
        mSDCardPath = getSdcardDir();
        if (mSDCardPath == null) {
            return false;
        }
        File f = new File(mSDCardPath, APP_FOLDER_NAME);
        if (!f.exists()) {
            try {
                f.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    private String getSdcardDir() {
        if (Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().toString();
        }
        return null;
    }

    //获取距离
    private void getDistance(LatLng endLng, LatLng startLng) {
        PlanNode enNodee = PlanNode.withLocation(endLng);
        PlanNode stNodee = PlanNode.withLocation(startLng);
        mSearch.drivingSearch((new DrivingRoutePlanOption())
                .from(enNodee).to(stNodee));

    }

    private void routeplanToNavi(final int coType, Double longitude, Double latitude, String name, String description) {
        if (!hasInitSuccess) {
            Toast.makeText(this, "还未初始化!", Toast.LENGTH_SHORT).show();
        }
        BNRoutePlanNode sNode = new BNRoutePlanNode(longitude, latitude, "百度大厦", "百度大厦", coType);
        BNRoutePlanNode eNode = null;
        if (tag == 1) {
            eNode = new BNRoutePlanNode(Double.valueOf(getOrderBean.getC_longitude()), Double.valueOf(getOrderBean.getC_latitude()), null, null, coType);
        } else if (tag == 2) {
            eNode = new BNRoutePlanNode(Double.valueOf(outOrderBean.getC_customerlongitude()), Double.valueOf(outOrderBean.getC_customerlatitude()), null, null, coType);
        }
        mStartNode = sNode;
        List<BNRoutePlanNode> list = new ArrayList<>();
        list.add(sNode);
        list.add(eNode);
        BaiduNaviManagerFactory.getCommonSettingManager().setMultiRouteEnable(true);
        BaiduNaviManagerFactory.getRoutePlanManager().routeplanToNavi(list, IBNRoutePlanManager.RoutePlanPreference.ROUTE_PLAN_PREFERENCE_DEFAULT, null, new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_START:
                        Toast.makeText(SendMapActivity.this, "算路开始", Toast.LENGTH_SHORT)
                                .show();
                        break;
                    case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_SUCCESS:
                        Toast.makeText(SendMapActivity.this, "算路成功", Toast.LENGTH_SHORT)
                                .show();
                        break;
                    case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_FAILED:
                        Toast.makeText(SendMapActivity.this, "算路失败", Toast.LENGTH_SHORT)
                                .show();
                        break;
                    case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_TO_NAVI:
                        Toast.makeText(SendMapActivity.this, "算路成功准备进入导航", Toast.LENGTH_SHORT)
                                .show();
                        Intent intent = new Intent(SendMapActivity.this,
                                DemoGuideActivity.class);
                        mLocationClient.stop();
//                        Bundle bundle = new Bundle();
//                        bundle.putSerializable(ROUTE_PLAN_NODE, mStartNode);
//                        intent.putExtras(bundle);
                        startActivity(intent);
                        break;
                    default:
                        // nothing
                        break;
                }
            }
        });
    }

    @Override
    public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

    }

    @Override
    public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

    }

    @Override
    public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

    }

    @Override
    public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {
        int finalDistance = 0;
        if (drivingRouteResult == null || drivingRouteResult.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
        }
        if (drivingRouteResult.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
            // 起终点或途经点地址有岐义，通过以下接口获取建议查询信息
            // result.getSuggestAddrInfo()
            Toast.makeText(this, "抱歉，起终点或途经点地址有岐义", Toast.LENGTH_SHORT).show();
            return;
        }
        if (drivingRouteResult.error == SearchResult.ERRORNO.NO_ERROR) {
            if (drivingRouteResult.getRouteLines().size() > 1) {
                int distance = 0;
                for (int i = 0; i < drivingRouteResult.getRouteLines().size(); i++) {
                    if (distance == 0) {
                        distance = drivingRouteResult.getRouteLines().get(i).getDistance();
                    } else if (distance <= drivingRouteResult.getRouteLines().get(i).getDistance()) {

                    } else if (distance > drivingRouteResult.getRouteLines().get(i).getDistance()) {
                        distance = drivingRouteResult.getRouteLines().get(i).getDistance();
                    }
                }
                finalDistance = distance;

            }
        } else if (drivingRouteResult.getRouteLines().size() == 1) {
            RouteLine route = drivingRouteResult.getRouteLines().get(0);
            finalDistance = route.getDistance();

        } else {
            Log.d("route result", "结果数<0");
            return;
        }
        mDistanceTv.setText("距离：" + String.valueOf(finalDistance) + "米");

    }

    @Override
    public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

    }

    @Override
    public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            city = location.getCity();
            longitude = location.getLongitude();
            latitude = location.getLatitude();
            int errorCode = location.getLocType();
            Log.d("111111", "errorCode:" + errorCode);
            if (errorCode == 161 || errorCode == 61) {
//                routeplanToNavi(BNRoutePlanNode.CoordinateType.BD09LL, location.getLongitude(), location.getLatitude(), location.getCity(), location.getCity());
//                mLocationClient.stop();
            }
            mBaiduMap.clear();
            BitmapDescriptor bitmap = BitmapDescriptorFactory
                    .fromResource(R.mipmap.car);
            BitmapDescriptor bitmap1 = BitmapDescriptorFactory
                    .fromResource(R.mipmap.location_red);

            //构建MarkerOption，用于在地图上添加Marker
            latLng = new LatLng(latitude, longitude);
            if (tag == 1) {
                latLng1 = new LatLng(getOrderBean.getC_latitude(), getOrderBean.getC_longitude());
            } else if (tag == 2) {
                latLng1 = new LatLng(outOrderBean.getC_customerlatitude(), outOrderBean.getC_customerlongitude());
            }

            OverlayOptions option = new MarkerOptions()
                    .position(latLng)
                    .icon(bitmap);
            OverlayOptions option1 = new MarkerOptions()
                    .position(latLng1)
                    .icon(bitmap1);
            getDistance(latLng, latLng1);
            //在地图上添加Marker，并显示
            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            builder.include(latLng);
            builder.include(latLng1);
            mBaiduMap.setMapStatus(MapStatusUpdateFactory
                    .newLatLngBounds(builder.build()));
            mBaiduMap.addOverlay(option);
            mBaiduMap.addOverlay(option1);

//            mDistanceTv.setText("距离：" + String.valueOf((int) DistanceUtil.getDistance(latLng, latLng1)) + "米");
            //画范围
            if (tag == 1) {

            } else if (tag == 2) {
                OverlayOptions ooCircle = new CircleOptions().fillColor(0x000000FF)
                        .center(latLng1).stroke(new Stroke(5, 0xAA000000))
                        .radius(250);
                mBaiduMap.addOverlay(ooCircle);
            }
            if (SpatialRelationUtil.isCircleContainsPoint(latLng1, 250, latLng)) {
                mNextTv.setText("确认送达");
                mNextTv.setBackgroundColor(Color.parseColor("#28c105"));

            } else {
                mNextTv.setText("等待送达");
                mNextTv.setBackgroundColor(Color.parseColor("#FF9E9E9E"));
            }
        }
    }

    private void setLocationClientOption() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        option.setScanSpan(20000);
        option.setOpenGps(true);
        option.setLocationNotify(true);
        option.setIgnoreKillProcess(false);
        option.SetIgnoreCacheException(false);
        option.setEnableSimulateGps(false);
        mLocationClient.setLocOption(option);
        option.setIsNeedAddress(true);
        option.setIsNeedLocationPoiList(true);

    }

    //司机端到达目的地
    private void initReachDestinationHtml(String c_id, String c_token, final View view) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("c_id", c_id);
        hashMap.put("c_token", c_token);
        hashMap.put("c_type", UrlValuse.TYPE);
        OkGoRequests.getInstance().putRequestAsync(UrlValuse.POST_API_DRIVER + UrlValuse.REACH_DESTINATION, hashMap, ReachDestinationRequestBean.class, new OkGoRequests.OnTrue<ReachDestinationRequestBean>() {
            @Override
            public void hasData(ReachDestinationRequestBean date) {
                if (date.isSuccess()) {
                    setPopW(view, date.getResult());
                } else {
                    BaseHint baseHint = new BaseHint.addHint().setParameter(SendMapActivity.this, "提示", date.getLocalizedMessage());
                    baseHint.show();
                }
            }
        }, new OkGoRequests.OnError<ReachDestinationRequestBean>() {
            @Override
            public void noData() {

            }
        });
    }

    private void setPopW(View v, ReachDestinationRequestBean.ResultBean datas) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_activity_send_map_popw, null);
        handleLogic(view, datas);
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(this).setView(view)
                .size(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)//显示大小
//                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
//                .setBgDarkAlpha(0.7f) // 控制亮度
                .enableOutsideTouchableDissmiss(false)// 设置点击PopupWindow之外的地方，popWindow不关闭，如果不设置这个属性或者为true，则关闭
                .setAnimationStyle(R.style.CustomPopWindowStyle) // 添加自定义显示和消失动画
                .create()
                .showAtLocation(v, Gravity.CENTER, 0, 0);
    }

    private void handleLogic(View contentView, final ReachDestinationRequestBean.ResultBean datas) {
        TextView nameTv = contentView.findViewById(R.id.item_activity_send_map_popw_name_tv);
        TextView numTv = contentView.findViewById(R.id.item_activity_send_map_popw_mun_tv);
        ImageView headIv = contentView.findViewById(R.id.item_activity_send_map_popw_head_iv);
        ImageView phoneTv = contentView.findViewById(R.id.item_activity_send_map_popw_phone_iv);
        nameTv.setText(datas.getC_name());
        numTv.setText("共" + datas.getC_parcelnumber() + "件");
        TextView onTv = contentView.findViewById(R.id.item_activity_send_map_on_tv);
        TextView offTv = contentView.findViewById(R.id.item_activity_send_map_off_tv);
        RequestOptions requestOptions = new RequestOptions()
                .placeholder(R.mipmap.order_driver_head)
                .error(R.mipmap.order_driver_head)
                .fallback(R.mipmap.order_driver_head);

        Glide.with(this)
                .load(datas.getC_headportrait())
                .apply(requestOptions)
                .into(headIv);
        RecyclerView recyclerView = contentView.findViewById(R.id.item_activity_send_map_popw_rv);
        SendMapPopwRlAdapter sendMapPopwRlAdapter = new SendMapPopwRlAdapter(R.layout.item_activity_send_map_popw_rv, datas.getCostomerWaybill());
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        recyclerView.setAdapter(sendMapPopwRlAdapter);
        onTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initDriverHandoverHtml(outOrderBean.getC_id(), token);
            }
        });
        offTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCustomPopWindow.dissmiss();
            }
        });
        phoneTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                if (ActivityCompat.checkSelfPermission(SendMapActivity.this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(SendMapActivity.this, Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(SendMapActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    String te1 = tm.getLine1Number();//获取本机号码
                    Log.d("SendMapActivity", te1);
                    return;
                }

                initSecretaxbHtml(datas.getC_account(), driverPhone, token);
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        mLocationClient.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stop();

    }

    //号码隐私保护
    private void initSecretaxbHtml(String c_numbera, String c_numberb, String c_token) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("c_numbera", c_numbera);
        hashMap.put("c_numberb", c_numberb);
        hashMap.put("c_type", UrlValuse.TYPE);
        hashMap.put("c_token", c_token);
        OkGoRequests.getInstance().putRequestAsync(UrlValuse.POST_API_BASE + UrlValuse.SECRETAXB, hashMap, SecretaxbRequestBean.class, new OkGoRequests.OnTrue<SecretaxbRequestBean>() {
            @Override
            public void hasData(SecretaxbRequestBean date) {
                if (date.isSuccess()) {
                    Intent myCallIntent = new Intent(Intent.ACTION_DIAL,
                            Uri.parse("tel:" + date.getResult().getC_secretno()));
                    startActivity(myCallIntent);
                }
            }
        }, new OkGoRequests.OnError<SecretaxbRequestBean>() {
            @Override
            public void noData() {

            }
        });
    }

    //司机端交接订单
    private void initDriverHandoverHtml(String c_id, String c_token) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("c_id", c_id);
        hashMap.put("c_token", c_token);
        hashMap.put("c_type", UrlValuse.TYPE);
        OkGoRequests.getInstance().putRequestAsync(UrlValuse.POST_API_DRIVER + UrlValuse.DRIVER_HANDOVER, hashMap, BaseBean.class, new OkGoRequests.OnTrue<BaseBean>() {
            @Override
            public void hasData(BaseBean date) {
                if (date.isSuccess()) {
                    BaseHint baseHint = new BaseHint.addHint().setParameter(SendMapActivity.this, "提示", "确认交接成功");
                    baseHint.show();
                    mCustomPopWindow.dissmiss();
                    getTag = 1;
                    mNextTv.setText("已交接");
                    mNextTv.setTextColor(Color.parseColor("#ffffff"));
                    mNextTv.setBackgroundColor(Color.parseColor("#979696"));
                } else {
                    BaseHint baseHint = new BaseHint.addHint().setParameter(SendMapActivity.this, "提示", date.getLocalizedMessage());
                    baseHint.show();
                    mCustomPopWindow.dissmiss();
                }
            }
        }, new OkGoRequests.OnError<BaseBean>() {
            @Override
            public void noData() {

            }
        });
    }

    private void initTTS() {
        // 使用内置TTS
        BaiduNaviManagerFactory.getTTSManager().initTTS(getApplicationContext(),
                getSdcardDir(), APP_FOLDER_NAME, "14688760");

        // 不使用内置TTS
//         BaiduNaviManagerFactory.getTTSManager().initTTS(mTTSCallback);

        // 注册同步内置tts状态回调
        BaiduNaviManagerFactory.getTTSManager().setOnTTSStateChangedListener(
                new IBNTTSManager.IOnTTSPlayStateChangedListener() {
                    @Override
                    public void onPlayStart() {
                        Log.e("BNSDKDemo", "ttsCallback.onPlayStart");
                    }

                    @Override
                    public void onPlayEnd(String speechId) {
                        Log.e("BNSDKDemo", "ttsCallback.onPlayEnd");
                    }

                    @Override
                    public void onPlayError(int code, String message) {
                        Log.e("BNSDKDemo", "ttsCallback.onPlayError" + message);
                    }
                }
        );

        // 注册内置tts 异步状态消息
        BaiduNaviManagerFactory.getTTSManager().setOnTTSStateChangedHandler(
                new Handler(Looper.getMainLooper()) {
                    @Override
                    public void handleMessage(Message msg) {
                        Log.e("BNSDKDemo", "ttsHandler.msg.what=" + msg.what);
                    }
                }
        );
    }


}
